/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reversepro(ListNode* begin , ListNode* end){
        if(begin->next == end){
            return begin;
        }
        ListNode* newhead = reversepro(begin->next , end);
        begin->next->next = begin;
        begin->next = nullptr;
        return newhead;
    }
    ListNode* reverseBetween(ListNode* head, int left, int right) {
        if(!head || !head->next || left == right){
            return head;
        }


        ListNode* dumbnode = new ListNode(0 , head);
        ListNode* pre = dumbnode;
        ListNode* end = dumbnode;
        for(int i = 0 ; i < left-1 ; ++i){
            pre = pre->next;
        }
        for(int i = 0 ; i < right + 1 ; ++i){
            end = end->next;
        }


        ListNode* e = reversepro(pre->next , end);
        pre->next->next = end;
        pre->next = e;
        return dumbnode->next;
    }
};